package com.ruoyi.moon.service.impl;

import com.github.houbb.sensitive.word.core.SensitiveWordHelper;
import com.ruoyi.common.config.MySensitiveWordReplace;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ScoreUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.moon.domain.*;
import com.ruoyi.moon.domain.vo.MyReviewsVO;
import com.ruoyi.moon.domain.vo.ReviewsInfoVO;
import com.ruoyi.moon.domain.vo.ScoreVo;
import com.ruoyi.moon.mapper.MoonCompanyMapper;
import com.ruoyi.moon.mapper.MoonReplyMapper;
import com.ruoyi.moon.mapper.MoonReviewsMapper;
import com.ruoyi.moon.mapper.MoonUpvoteMapper;
import com.ruoyi.moon.service.IMoonNoticeService;
import com.ruoyi.moon.service.IMoonNoticeTemplateService;
import com.ruoyi.moon.service.IMoonReviewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Array;
import java.util.*;

/**
 * 评论Service业务层处理
 *
 * @author admin
 * @date 2024-11-05
 */
@Service
@Slf4j
public class MoonReviewsServiceImpl implements IMoonReviewsService {
    @Autowired
    private MoonReviewsMapper moonReviewsMapper;
    @Autowired
    private MoonReplyMapper moonReplyMapper;

    @Autowired
    private MoonCompanyMapper moonCompanyMapper;
    @Autowired
    private IMoonNoticeService moonNoticeService;
    @Autowired
    private MoonUpvoteMapper moonUpvoteMapper;
    @Autowired
    private IMoonNoticeTemplateService moonNoticeTemplateService;

    /**
     * 查询评论
     *
     * @param id 评论主键
     * @return 评论
     */
    @Override
    public MoonReviews selectMoonReviewsById(Long id) {
        return moonReviewsMapper.selectMoonReviewsById(id);
    }

    /**
     * 查询评论列表
     *
     * @param moonReviews 评论
     * @return 评论
     */
    @Override
    public List<MoonReviews> selectMoonReviewsList(MoonReviews moonReviews) {
        return moonReviewsMapper.selectMoonReviewsList(moonReviews);
    }

    /**
     * 新增评论
     *
     * @param moonReviews 评论
     * @return 结果
     */

    @Override
    public int insertMoonReviews(MoonReviews moonReviews) {
        String description = SensitiveWordHelper.replace(moonReviews.getDetailedDescription(), new MySensitiveWordReplace());
        moonReviews.setDetailedDescription(description);
        moonReviews.setCreateTime(DateUtils.getNowDate());
        moonReviews.setAuditStatus("2");
        //发送消息
//        MoonNoticeTemplate moonNoticeTemplate = new MoonNoticeTemplate();
//        moonNoticeTemplate.setTemplateType(1L);
//        moonNoticeTemplate.setTemplateState(0);
//        List<MoonNoticeTemplate> noticeTemplates = moonNoticeTemplateService.selectMoonNoticeTemplateList(moonNoticeTemplate);
//        String statusText;
//        String auditStatus = "2";
//        if (auditStatus.equals("2")) {
//            statusText = "审核等待中";
//        } else {
//            statusText = "未知状态";
//        }
//        for (MoonNoticeTemplate template : noticeTemplates) {
//            MoonNotice notice = new MoonNotice();
//            String noticeContent = template.getTemplateContent();
//            if (moonReviews.getCompanyName() != null) {
//                noticeContent = noticeContent.replaceAll("\\$\\{companyName\\}", moonReviews.getCompanyName())
//                        .replaceAll("\\$\\{statusText\\}", statusText);
//            }
//            notice.setNoticeContent(noticeContent);
//            notice.setNoticeTitle(template.getTemplateTitle());
//            if (moonReviews.getUserId() != null) {
//                notice.setUserId(Long.valueOf(moonReviews.getUserId()));
//                moonNoticeService.insertMoonNotice(notice);
//            }
//        }
        int i = moonReviewsMapper.insertMoonReviews(moonReviews);
        moonReviews.setAuditStatus("0");
        auditSubmit(moonReviews);
        return i;
    }

    public static void main(String[] args) {
        String description = SensitiveWordHelper.replace("恶心垃圾老板东西草泥马", new MySensitiveWordReplace());

        System.out.println(description);
    }

    /**
     * 修改评论
     *
     * @param moonReviews 评论
     * @return 结果
     */
    @Override
    public int updateMoonReviews(MoonReviews moonReviews)
    {
        return moonReviewsMapper.updateMoonReviews(moonReviews);
    }

    /**
     * 批量删除评论
     *
     * @param ids 需要删除的评论主键
     * @return 结果
     */
    @Override
    public int deleteMoonReviewsByIds(Long[] ids)
    {
        // 删除评论与回复关联
        moonReplyMapper.deleteReviewsReply(ids);
        // 删除评论与点赞关联
        moonUpvoteMapper.deleteReviewsUpvote(ids);
        return moonReviewsMapper.deleteMoonReviewsByIds(ids);
    }

    /**
     * 删除评论信息
     *
     * @param id 评论主键
     * @return 结果
     */
    //@TODO 删除点评连带删除它所有回复、赞踩(待完成)
    @Override
    public int deleteMoonReviewsById(Long id) {
        moonReplyMapper.deleteReviewsReplyById(id);
        moonUpvoteMapper.deleteReviewsUpvoteById(id);
        MoonReviews moonReviews = moonReviewsMapper.selectMoonReviewsById(id);
        int i = moonReviewsMapper.deleteMoonReviewsById(id);
        MoonCompany company = moonCompanyMapper.selectMoonCompanyById(moonReviews.getCompanyId());
        //查询用户是否第一次评论
        MoonReviews c = new MoonReviews();
        c.setCompanyId(company.getId());
        c.setUserId(moonReviews.getUserId());
        c.setAuditStatus("0");
        List<MoonReviews> list = moonReviewsMapper.selectMoonReviewsList(c);
        if (list.size() < 2) {
            // 计算公司评分
            List<ScoreVo> scoreVos = moonReviewsMapper.selectScore(company.getId());
            ArrayList<Double> n = new ArrayList<>();
            for (ScoreVo r : scoreVos) {
                n.add(r.getTotalCompanyRating());
            }
            MoonCompany moonCompany = new MoonCompany();
            if (n.size() > 0) {
                String score = ScoreUtil.getscore(n);
                moonCompany.setCompanyRating(Double.valueOf(score));
            } else {
                moonCompany.setCompanyRating(0.0);
            }
            moonCompany.setId(company.getId());
            moonCompanyMapper.updateRating(moonCompany);
        }
        return i;
    }


    @Override
    public MoonReviews selectDetails(Long id) {
        return moonReviewsMapper.selectDetails(id);
    }


    /**
     * 我的评价
     *
     * @param userId 评论主键
     * @return 结果
     */
    @Override
    public List<MyReviewsVO> selectMoonEvaluate(Long userId) {
        return moonReviewsMapper.selectMoonEvaluate(userId);

    }

    @Override
    @Transactional
    public List<ReviewsInfoVO> selectReviewsInfo(Long id) {
        List<ReviewsInfoVO> reviewsInfoVOList = moonReviewsMapper.selectReviewsInfo(id);
        if (reviewsInfoVOList.isEmpty()) {
            return Collections.emptyList();
        }
        boolean isLogin = SecurityUtils.isLogin();
        if (isLogin) {
            Long userId = SecurityUtils.getUserId();
            for (ReviewsInfoVO r : reviewsInfoVOList) {
                MoonUpvote upvoteCheck = new MoonUpvote();
                upvoteCheck.setUserId(userId);
                upvoteCheck.setComReviewsId(r.getId());
                upvoteCheck.setType("0");
                List<MoonUpvote> upvotes = moonUpvoteMapper.selectMoonUpvoteList(upvoteCheck);
                if (CollectionUtils.isNotEmpty(upvotes)) {
                    r.setIsUpvote(true);
                } else {
                    upvoteCheck.setType("1");
                    List<MoonUpvote> downvotes = moonUpvoteMapper.selectMoonUpvoteList(upvoteCheck);
                    if (CollectionUtils.isNotEmpty(downvotes)) {
                        r.setIsTrample(true);
                    }
                }
            }
        }
        // 设置dianzan和chaping的默认值为0
        for (ReviewsInfoVO reviews : reviewsInfoVOList) {

            if (reviews.getDianzan() == null) {
                reviews.setDianzan("0");
            }
            if (reviews.getChaping() == null) {
                reviews.setChaping("0");
            }
        }
        return reviewsInfoVOList;
    }


    @Override
    public AjaxResult auditSubmit(MoonReviews moonReviews) {

        // 查询对象
        MoonReviews reviews = moonReviewsMapper.selectMoonReviewsById(moonReviews.getId());
        if (reviews == null) {
            throw new IllegalArgumentException("请联系管理员");
        }


        String companyName = reviews.getCompanyName();
        if (companyName == null || companyName.trim().isEmpty()) {
            throw new IllegalArgumentException("公司名称为空");
        }
        MoonCompany company = moonCompanyMapper.selectMoonCompanyById(moonReviews.getCompanyId());
//        List<MoonCompany> companyList = moonCompanyMapper.selectMoonCompany(reviews.getCompanyName());
//        if (!companyList.isEmpty()) {
        // 替换敏感词
        String replacedDescription = SensitiveWordHelper.replace(reviews.getDetailedDescription(), new MySensitiveWordReplace());
        reviews.setDetailedDescription(replacedDescription);
        reviews.setAuditStatus(moonReviews.getAuditStatus());
        reviews.setCause(moonReviews.getCause());
        // 更新评论
        moonReviewsMapper.updateMoonReviews(reviews);

        //查询用户是否第一次评论
        MoonReviews c = new MoonReviews();
        c.setCompanyId(company.getId());
        c.setUserId(moonReviews.getUserId());
        c.setAuditStatus("0");
        List<MoonReviews> list = moonReviewsMapper.selectMoonReviewsList(c);
        if(list.size() < 2){
            // 计算公司评分
            List<ScoreVo> scoreVos = moonReviewsMapper.selectScore(company.getId());
            ArrayList<Double> n = new ArrayList<>();
            for(ScoreVo r : scoreVos){
                n.add(r.getTotalCompanyRating());
            }
            String score = ScoreUtil.getscore(n);
            MoonCompany moonCompany = new MoonCompany();
            moonCompany.setId(company.getId());
            moonCompany.setCompanyRating(Double.valueOf(score));
            moonCompanyMapper.updateRating(moonCompany);
        }

//        reviews.setCompanyId(company.getId());


          /*  List<ScoreVo> score = moonReviewsMapper.selectScore(company.getId());
            Map<Long, Double> companyRatings = new HashMap<>();
            for (ScoreVo Info : score) {
                Double rating = Info.getTotalCompanyRating();
                Integer totalPeople = Info.getTotalPeople();
                if (totalPeople != null && totalPeople != 0) {
                    Double avgRating = rating / totalPeople;
                    // 限制评分不超过10分
                    avgRating = Math.min(avgRating, 10.0);
                    Long companyId = reviews.getCompanyId();
                    // 将公司ID和平均分存储在Map中
                    companyRatings.put(companyId, avgRating);
                } else {
                    Info.setAug(0.0);
                }
            }
            // 遍历Map并更新数据库中的公司评分
            for (Map.Entry<Long, Double> entry : companyRatings.entrySet()) {
                MoonCompany moonCompany = new MoonCompany();
                moonCompany.setId(entry.getKey());
                moonCompany.setCompanyRating(entry.getValue());
                moonCompanyMapper.updateRating(moonCompany);
            }*/
//        } else {
//            MoonCompany newCompany = new MoonCompany();
//            String replacedDescription = SensitiveWordHelper.replace(reviews.getDetailedDescription(), new MySensitiveWordReplace());
//            newCompany.setCompanName(reviews.getCompanyName());
//            newCompany.setCompanyRating(reviews.getCompanyRating());
//            newCompany.setCreateTime(DateUtils.getNowDate());
//            // 插入新公司并获取生成的ID
//            moonCompanyMapper.insertMoonCompany(newCompany);
//            Long  companyId = newCompany.getId();
//            // 替换敏感词
//            reviews.setDetailedDescription(replacedDescription);
//            reviews.setCompanyId(companyId);
//            reviews.setAuditStatus(moonReviews.getAuditStatus());
//            reviews.setCause(moonReviews.getCause());
//            moonReviewsMapper.updateMoonReviews(reviews);
//
//        }
        //发送消息
//        MoonNoticeTemplate moonNoticeTemplate = new MoonNoticeTemplate();
//        moonNoticeTemplate.setTemplateType(1L);
//        moonNoticeTemplate.setTemplateState(0);
//        List<MoonNoticeTemplate> noticeTemplates = moonNoticeTemplateService.selectMoonNoticeTemplateList(moonNoticeTemplate);
//        String statusText;
//        String auditStatus = moonReviews.getAuditStatus();
//        if (auditStatus.equals("0")) {
//            statusText = "审核通过";
//        } else if (auditStatus.equals("1")) {
//            statusText = "审核未通过,未通过原因:"+moonReviews.getCause();
//        } else if (auditStatus.equals("2")) {
//            statusText = "审核等待中";
//        } else {
//            statusText = "未知状态";
//        }
//        for (MoonNoticeTemplate template : noticeTemplates) {
//            MoonNotice notice = new MoonNotice();
//            String noticeContent = template.getTemplateContent();
//            if (reviews.getCompanyName() != null) {
//                noticeContent = noticeContent.replaceAll("\\$\\{companyName\\}", reviews.getCompanyName())
//                        .replaceAll("\\$\\{statusText\\}", statusText);
//            }
//            notice.setNoticeContent(noticeContent);
//            notice.setNoticeTitle(template.getTemplateTitle());
//            if (reviews.getUserId() != null) {
//                notice.setUserId(Long.valueOf(reviews.getUserId()));
//                moonNoticeService.insertMoonNotice(notice);
//            }
//        }
        return AjaxResult.success();
    }


    @Override
    public boolean deleteMoonReviews(Long id, Long userId) {
        moonReplyMapper.deleteReply(id, userId);
        moonUpvoteMapper.deleteUpvote(id, userId);
        return moonReviewsMapper.deleteMoonReviews(id, userId);
    }


}
